package com.rockcent.third.helper;

import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;


/**
 * Created by Antinomy on 16/4/1.
 *
 * 各个分销码 生成器
 *
 */
@Component
public class CodeHelper {

    private static final String mallSaleCodePrefix = "M@";
    private static final String merchantSaleCodePrefix = "B@";
    private static final String customerShareCodePrefix = "C@";
    private static final String requiredCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private MallRepository mallRepository;


    /**
     * 生产merchant 的分销码
     * @return
     */
    public String genMerchantSaleCode() {
        String shareCode = this.genShareCode(merchantSaleCodePrefix);
        while (true) {
            Merchant merchant = merchantRepository.findBySalesCode(shareCode);
            if (merchant == null) {
                return shareCode;
            }
            continue;
        }
    }

    /**
     * 生产 mall 的分销码
     * @return
     */
    public String genMallSaleCode() {
        String shareCode = this.genShareCode(mallSaleCodePrefix);
        while (true) {
            Mall mall = mallRepository.findBySalesCode(shareCode);
            if (mall == null) {
                return shareCode;
            }
            continue;
        }
    }



    private String genShareCode(String codePrefix) {
        Random random = new Random();
        String result = codePrefix;
        for (int i = 0; i < 7; i++) {
            result += requiredCharacters.charAt(random.nextInt(62));
        }
        return result;
    }

}
